package com.mdinic.blogovi.model;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.roo.addon.dod.RooDataOnDemand;
import org.springframework.stereotype.Component;

@Configurable
@Component
@RooDataOnDemand(entity = Fav.class)
public class FavDataOnDemand {

    private final Random rnd = new SecureRandom();

    private List<Fav> data;

    @Autowired
    private PersonDataOnDemand personDataOnDemand;

    @Autowired
    private BlogPostDataOnDemand blogPostDataOnDemand;

    public Fav getNewTransientFav(int index) {
        Fav obj = new Fav();
        setPerson(obj, index);
        setPost(obj, index);
        return obj;
    }

    public void setPerson(Fav obj, int index) {
        Person person = personDataOnDemand.getRandomPerson();
        obj.setPerson(person);
    }

    public void setPost(Fav obj, int index) {
        BlogPost post = blogPostDataOnDemand.getRandomBlogPost();
        obj.setPost(post);
    }

    public Fav getSpecificFav(int index) {
        init();
        if (index < 0) {
            index = 0;
        }
        if (index > (data.size() - 1)) {
            index = data.size() - 1;
        }
        Fav obj = data.get(index);
        Long id = obj.getId();
        return Fav.findFav(id);
    }

    public Fav getRandomFav() {
        init();
        Fav obj = data.get(rnd.nextInt(data.size()));
        Long id = obj.getId();
        return Fav.findFav(id);
    }

    public boolean modifyFav(Fav obj) {
        return false;
    }

    public void init() {
        int from = 0;
        int to = 10;
        data = Fav.findFavEntries(from, to);
        if (data == null) {
            throw new IllegalStateException("Find entries implementation for 'Fav' illegally returned null");
        }
        if (!data.isEmpty()) {
            return;
        }

        data = new ArrayList<Fav>();
        for (int i = 0; i < 10; i++) {
            Fav obj = getNewTransientFav(i);
            try {
                obj.persist();
            } catch (ConstraintViolationException e) {
                StringBuilder msg = new StringBuilder();
                for (Iterator<ConstraintViolation<?>> iter = e.getConstraintViolations().iterator(); iter.hasNext();) {
                    ConstraintViolation<?> cv = iter.next();
                    msg.append("[").append(cv.getConstraintDescriptor()).append(":").append(cv.getMessage())
                            .append("=").append(cv.getInvalidValue()).append("]");
                }
                throw new RuntimeException(msg.toString(), e);
            }
            obj.flush();
            data.add(obj);
        }
    }
}
